<template>
  <div class="app-container falseTabel-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-input v-model="formInline.name" placeholder="请输入名称" @keyup.enter.native="searchClick"></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addEditClick(1)">新建</el-button>
      </el-form>
      <!-- 表格 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="名称" prop="name"></el-table-column>
        <el-table-column align="center" label="分类" prop="type_name"></el-table-column>
        <el-table-column align="center" label="等级" prop="grade_name"></el-table-column>
        <el-table-column align="center" label="余额限制" prop="limit"></el-table-column>
        <el-table-column align="center" label="初始余额" prop="init"></el-table-column>
        <el-table-column align="center" label="有效期" prop="valid"></el-table-column>
        <el-table-column align="center" label="操作" width="260px">
          <template slot-scope="scope">
            <el-button
              @click="addEditClick(2,scope.row.id,scope.row.enable_update)"
              type="primary"
              plain
              size="mini"
            >编辑</el-button>
            <el-button @click="addEditClick(3,scope.row.id)" type="primary" plain size="mini">详情</el-button>
            <el-button @click="delClick(scope.row.id)" type="danger" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增编辑弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="500px"
        :visible.sync="addEditDialog"
        append-to-body
      >
        <el-form
          :model="saveForm"
          ref="saveForm"
          :rules="rules"
          class="demo-form-inline"
          label-width="80px"
        >
          <el-form-item label="名称" prop="name">
            <el-input :disabled="tab==3" :maxlength="8" placeholder="请输入名称" v-model="saveForm.name"></el-input>
          </el-form-item>
          <el-form-item label="说明" prop="describe">
            <el-input
              :disabled="tab==3"
              type="textarea"
              :maxlength="150"
              :rows="3"
              v-model="saveForm.describe"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类" prop="type">
            <el-select v-model="saveForm.type" style="width:120px" :disabled="tab==3||isDisabled" @change="switchType">
              <el-option
                v-for="item in type_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="等级" prop="grade">
            <el-select v-model="saveForm.grade" style="width:120px" :disabled="tab==3||isDisabled">
              <el-option
                v-for="item in grade_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="有效期" prop="valid_day">
            <el-input
              :maxlength="8"
              placeholder="输入值大于0"
              :disabled="tab==3||isDisabled"
              v-model.number="saveForm.valid_day"
              style="width:120px;margin-right:10px"
            ></el-input>天
          </el-form-item>
          <el-form-item label="余额限制" prop="is_limit">
            <el-select
              @change="limitChange"
              v-model="saveForm.is_limit"
              style="width:120px"
              :disabled="tab==3||isDisabled"
            >
              <el-option
                v-for="item in limit_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <div v-show="saveForm.is_limit=='1'" style="display:flex">
            <el-form-item label="初始余额" prop="initial_balance">
              <el-input
                :maxlength="8"
                placeholder="输入值大于0"
                :disabled="tab==3||isDisabled"
                v-model.number="saveForm.initial_balance"
                style="width:120px;"
              ></el-input>（可选）
            </el-form-item>
            <el-form-item label-width="20px" prop="is_cancel">
              <el-checkbox
                label="余额为0是否自动注销"
                :disabled="tab==3||isDisabled"
                true-label="1"
                false-label="0"
                v-model="saveForm.is_cancel"
              ></el-checkbox>
            </el-form-item>
          </div>
          <div style="display:flex;">
            <el-form-item label="拥有上限" prop="have_toplimit">
              <el-input
                :maxlength="8"
                v-model.number="saveForm.have_toplimit"
                :disabled="tab==3||isDisabled"
                style="width:120px;"
              ></el-input>
            </el-form-item>
            <el-form-item label-width="20px" prop="is_vip_sell" v-show="saveForm.type==0">
              <el-radio v-model="saveForm.is_vip_sell" label="1" :disabled="tab==3">会员价</el-radio>
              <el-radio v-model="saveForm.is_vip_sell" label="0" :disabled="tab==3">非会员价</el-radio>
            </el-form-item>
          </div>
        </el-form>
        <div v-show="tab<3" slot="footer" class="dialog-footer">
          <el-button @click="addEditDialog=false" size="small">取 消</el-button>
          <el-button type="primary" @click="saveClick" size="small">保 存</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :page-count="totalPageNumber"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getPage,
  getInfo,
  setCard,
  delCard,
} from "@/api/platformSet/cardTypeManager";
import { notCharmap, positiveInt, null0to } from "@/utils/validate";
export default {
  data() {
    const vName = (rule, value, callback) => {
      if (this.tab != 3) {
        if (!value) {
          callback(new Error("请输入名称"));
        } else {
          if (!notCharmap(value)) {
            callback(new Error("名称只能为数字、字母、下划线和汉字"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    const vDay = (rule, value, callback) => {
      if (this.tab != 3) {
        if (value === "") {
          callback(new Error("请输入有效期"));
        } else {
          if (!positiveInt(value)) {
            callback(new Error("有效期只能为正整数"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    const vInit = (rule, value, callback) => {
      if (this.tab != 3 && value !== "") {
        if (!positiveInt(value)) {
          callback(new Error("初始余额只能为空或正整数"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const vTop = (rule, value, callback) => {
      if (this.tab != 3) {
        if (value === "") {
          callback(new Error("请输入拥有上限"));
        } else if (!null0to(value)) {
          callback(new Error("拥有上限只能为大于等于0的整数"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const vipSell = (rule, value, callback) => {
      if(this.saveForm.type == 0 &&value == ''){
        callback(new Error("在选择币卡的情况下,还需选择是会员卡还是非会员卡"));
      }else{
        callback();
      }
    };
    return {
      list: null,
      type_list: [
        { id: "0", name: "币" },
        { id: "1", name: "次" },
        { id: "2", name: "星星" },
      ],
      grade_list: [
        { id: "0", name: "无" },
        { id: "1", name: "1级" },
        { id: "2", name: "2级" },
        { id: "3", name: "3级" },
        { id: "4", name: "4级" },
        { id: "5", name: "5级" },
        { id: "6", name: "6级" },
        { id: "7", name: "7级" },
        { id: "8", name: "8级" },
        { id: "9", name: "9级" },
      ],
      limit_list: [
        { id: "0", name: "无限" },
        { id: "1", name: "有限" },
      ],
      listLoading: false,
      addEditDialog: false,
      isDisabled: true,
      tab: 1,
      currentPage: 1,
      totalPageNumber: 1,
      oldCardData: {},
      formInline: {
        name: "",
      },
      saveForm: {
        id: "",
        name: "",
        describe: "",
        type: "0",
        grade: "0",
        valid_day: "",
        is_limit: "0",
        initial_balance: "",
        is_cancel: "0",
        have_toplimit: "1",
        update_time: "",
        is_vip_sell: ""
      },
      rules: {
        name: [{ required: false, validator: vName, trigger: "blur" }],
        valid_day: [{ required: false, validator: vDay, trigger: "blur" }],
        initial_balance: [
          { required: false, validator: vInit, trigger: "blur" },
        ],
        have_toplimit: [{ required: false, validator: vTop, trigger: "blur" }],
        is_vip_sell: [{required: false, validator: vipSell, trigger: "blur"}]
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.list) {
        vm.searchClick();
      }
    });
  },
  methods: {
    switchType(val){
       if(val != 0){
         this.saveForm.is_vip_sell = '';
       }
    },
    addEditClick(i, id, isEdit) {
      this.addEditDialog = true;
      this.tab = i;
      this.isDisabled = isEdit == 1;
      this.oldCardData = {};
      if (id) {
        getInfo({ id }).then((res) => {
          if (res.code == 1) {
            res.data.valid_day = Math.ceil(res.data.valid_day / 8.64e4);
            res.data.describe = res.data.describe ? res.data.describe : "";
            res.data.initial_balance =
              res.data.initial_balance == 0 ? "" : res.data.initial_balance;
            this.saveForm = res.data;
            this.oldCardData = JSON.parse(JSON.stringify(res.data));
            this.$refs.saveForm.resetFields();
          }
        });
      } else {
        this.isDisabled = false;
        this.saveForm.id = "";
        this.saveForm.update_time = "";
        this.$nextTick(() => {
          this.$refs.saveForm.resetFields();
        });
      }
    },
    limitChange(val) {
      if (val == 0) {
        this.saveForm.initial_balance = "";
        this.saveForm.is_cancel = "0";
      }
    },
    delClick(id) {
      this.$confirm("此操作删除，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delCard({ id }).then((res) => {
          if (res.code == 1) {
            this.$message.success(res.message);
            this.fetchData();
          }
        });
      });
    },
    saveClick() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          if (this.tab == 2) {
            if (
              JSON.stringify(this.oldCardData) == JSON.stringify(this.saveForm)
            ) {
              this.addEditDialog = false;
              return;
            }
            this.$confirm(
              "若该类型卡已在线上正常使用，修改内容保存后用户即可见，请慎重操作！",
              "提示",
              {
                confirmButtonText: "继续保存",
                cancelButtonText: "取消",
                type: "warning",
              }
            ).then(() => {
              this.save();
            });
          } else {
            this.save();
          }
        }
      });
    },
    save() {
      setCard(this.saveForm).then((res) => {
        if (res.code == 1) {
          this.addEditDialog = false;
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },
    // 搜索
    searchClick() {
      this.fetchData();
    },
    getData(data) {
      data.forEach((val) => {
        val.type_name = val.type == 0 ? "币" : val.type == 1 ? "次" : "星星";
        val.grade_name = val.grade == 0 ? "无" : val.grade + "级";
        val.limit = val.is_limit == 0 ? "无限" : "有限";
        val.init = val.initial_balance == 0 ? "无" : val.initial_balance;
        val.valid = Math.ceil(val.valid_day / 8.64e4) + "天";
      });
      this.list = data;
      this.listLoading = false;
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then((response) => {
          this.totalPageNumber = response.data.page;
          getList(this.formInline)
            .then((res) => {
              this.getData(res.data);
            })
            .catch((res) => {
              this.listLoading = false;
            });
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val)
        .then((res) => {
          this.getData(res.data);
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
  },
};
</script>